package io.admin.modules.sys.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.qiniu.util.StringUtils;
import io.admin.common.annotation.LogOperation;
import io.admin.common.constant.Constant;
import io.admin.common.page.PageData;
import io.admin.common.utils.ExcelUtils;
import io.admin.common.utils.Result;
import io.admin.common.validator.AssertUtils;
import io.admin.common.validator.ValidatorUtils;
import io.admin.common.validator.group.AddGroup;
import io.admin.common.validator.group.DefaultGroup;
import io.admin.common.validator.group.UpdateGroup;
import io.admin.modules.security.password.PasswordUtils;
import io.admin.modules.sys.dto.PasswordDTO;
import io.admin.modules.sys.dto.SysUserDTO;
import io.admin.modules.sys.dto.UserDTO;
import io.admin.modules.sys.dto.UserProjectDTO;
import io.admin.modules.sys.excel.UserExcel;
import io.admin.modules.sys.service.UserProjectService;
import io.admin.modules.sys.service.UserService;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 用户表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-07-04
 */
@RestController
@RequestMapping("sysapp/user")
@Api(tags="用户表")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserProjectService userProjectService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
   /* @RequiresPermissions("sys:user:page")*/
    public Result<PageData> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData page = userService.page(params);
        return new Result<PageData>().ok(page);
    }

    @GetMapping("pageByPro")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    /* @RequiresPermissions("sys:user:page")*/
    public Result<PageData<UserDTO>> pageByPro(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<UserDTO> page = userService.pageByPro(params);
        return new Result<PageData<UserDTO>>().ok(page);
    }
    @GetMapping("getUserListPro")
    @ApiOperation("分页")
    /* @RequiresPermissions("sys:user:page")*/
    public Result<List<UserDTO>> getUserListPro(@ApiIgnore @RequestParam Map<String, Object> params){
        List<UserDTO> list = userService.listByPro(params);
        return new Result<List<UserDTO>>().ok(list);
    }
    @GetMapping("getUserListProStr")
    @ApiOperation("分页")
    /* @RequiresPermissions("sys:user:page")*/
    public Result getUserListProStr(@ApiIgnore @RequestParam Map<String, Object> params){
       String str =findUserListProStr(params);
        if(StringUtils.isNullOrEmpty(str)){
            return new Result().ok("");
        }else{
          return new Result<>().ok(str);
        }
    }
    public String findUserListProStr( Map<String, Object> params){
        List<UserDTO> list = userService.listByPro(params);
        if(CollectionUtils.isEmpty(list)){
           return null;
        }else{
            List<String> s =  list.stream().map(i->String.valueOf(i.getId())).collect(Collectors.toList());
            return StringUtils.join(s,",");
        }

    }

    @GetMapping("{id}")
    @ApiOperation("信息")
   /* @RequiresPermissions("sys:user:info")*/
    public Result<UserDTO> get(@PathVariable("id") Long id){
        UserDTO data = userService.get(id);
        data.setPassword("");
        return new Result<UserDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
   /* @RequiresPermissions("sys:user:save")*/
    public Result save(@RequestBody UserDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        if(!StringUtil.isNullOrEmpty(dto.getPassword())){
            dto.setPassword( DigestUtil.sha256Hex(dto.getPassword()));
        }
        dto.setCreateDate(new Date());
        userService.save(dto);
        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
  /*  @RequiresPermissions("sys:user:update")*/
    public Result update(@RequestBody UserDTO dto){
        //效验数据
        if(!StringUtil.isNullOrEmpty(dto.getPassword())){
            dto.setPassword( DigestUtil.sha256Hex(dto.getPassword()));
        }
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        userService.update(dto);

        return new Result();
    }



    @PutMapping("password")
    @ApiOperation("修改密码")
    @LogOperation("修改密码")
    public Result password(@RequestBody UserDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto);
        dto.setPassword( DigestUtil.sha256Hex(dto.getPassword()));
        userService.update(dto);
        return new Result();
    }
    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    /*@RequiresPermissions("sys:user:delete")*/
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        userService.delete(ids);
        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
   /* @RequiresPermissions("sys:user:export")*/
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<UserDTO> list = userService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "用户表", list, UserExcel.class);
    }

    @RequestMapping("/saveUserPro")
    /*  @RequiresPermissions("sys:user:update")*/
    public Result saveUserPro(@RequestBody UserProjectDTO dto){
        log.info("开始新增用户和项目数据");
         String[] userIdArray= dto.getUserIds().split(",");
        String[] roleArray= dto.getRoles().split(",");
         if(userIdArray.length == 0 || null==dto.getProjectId()){
             return new Result().error("数据错误");
         }
         int index =0;
         Map<String,Object> params =new HashMap<>(2);
         params.put("projectId",dto.getProjectId());
         String str =findUserListProStr(params);
        for (String userId:userIdArray) {
            UserProjectDTO userProjectDTO =new UserProjectDTO();
            if(StringUtils.isNullOrEmpty(str)){
                userProjectDTO.setUserId(Long.valueOf(userId));
                userProjectDTO.setProjectId(dto.getProjectId());
                userProjectDTO.setProjectRole(Integer.valueOf(roleArray[index]));
                userProjectService.save(userProjectDTO);
            }else{
                if(!str.contains(userId)){
                    userProjectDTO.setUserId(Long.valueOf(userId));
                    userProjectDTO.setProjectId(dto.getProjectId());
                    userProjectDTO.setProjectRole(Integer.valueOf(roleArray[index]));
                    userProjectDTO.setCreateDate(new Date());
                    userProjectService.save(userProjectDTO);
                }
            }

            index++;
        }
        return new Result().ok("");
    }

    @RequestMapping("/deleteUserProjectSub")
    @LogOperation("删除")
    public Result deleteUserProjectSub(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        userProjectService.delete(ids);
        return new Result();
    }

    @RequestMapping("/userCount")
    public  Result userCount(HttpServletRequest request, HttpServletResponse response){
        return new  Result<>().ok(userService.userCount());
    }

}